package day20180131.designMode.fourteen_Flyweight;

import java.util.HashMap;

/**
 * Created by 14394 on 2018/1/31.
 */

//数据对象抽象
public abstract class Flyweight {
    //内部状态
    private String inState;

    //外部状态
    protected final String outState;

    public Flyweight(String outState) {
        this.outState = outState;
    }

    public String getInState() {
        return inState;
    }

    public void setInState(String inState) {
        this.inState = inState;
    }

    abstract void operate();
}

//实际数据对象
class FlyweightReall extends Flyweight{

    public FlyweightReall(String outState){
        super(outState);
    }

    @Override
    void operate() {
        System.out.println(outState + "operate");
    }
}

class FlyweightFactory{
    //定义一池容量
    private static HashMap<String,Flyweight> pool = new HashMap<>();

    public static Flyweight getFlyweight(String outState){

        //结果数据
        Flyweight flyweight = null;

        if (pool.containsKey(outState)){
            //池中又该对象，获取该对象
            flyweight = pool.get(outState);
        }else {
            //池中无该对象，创建并放入池中
            flyweight = new FlyweightReall(outState);
            pool.put(outState,flyweight);
        }

        return flyweight;
    }


    /*使用场景：    系统中存在大量相似对象
    *              细粒度的对象都具备较接近的外部状态，而且内部状态与环境无关
    *              需要缓冲池的场景
    *
    * */
    public static void main(String[] args) {
        Flyweight flyweight= FlyweightFactory.getFlyweight("data1");
        flyweight.operate();

        flyweight= FlyweightFactory.getFlyweight("data2");
        flyweight.operate();

        flyweight= FlyweightFactory.getFlyweight("data1");
        flyweight.operate();
    }
}
